<template>
  <div>
    <yt-crud
      v-bind="options"
      ref="crudRef"
      @onLoad="getData"
      :fun-props="{
        exportBtn: false,
        delBtn: false,
        addPermi: ['business:charger:add'],
      }"
      :table-props="{
        selection: true,
        delBtn: true,
        viewBtn: false,
        editBtn: true,
        menuSlot: true,
        menuWidth: 300,
        viewPermi: ['business:charger:query'],
        editPermi: ['business:charger:edit'],
        delPermi: ['business:charger:delete'],
      }"
      :loading="state.loading"
      :total="state.total"
      v-model:page="state.page"
      v-model:query="state.query"
      @delFun="handleDelete"
      @saveFun="onSave"
      @openBeforeFun="openBeforeFun"
      @change="onChange"
    >
      <template #online="scope:any">
        <DictTag :options="OnlineStatusEnum" :value="scope.row.online" />
      </template>

      <template #status="scope:any">
        <el-switch
          v-has-permi="['business:charger:edit']"
          v-model="scope.row.status"
          active-value="Enabled"
          inactive-value="Disabled"
          @change="handleStatusChange(scope.row)"
        />
        <DictTag v-has-no-permi="['business:charger:edit']" :options="EnableStatusEnum" :value="scope.row.status" />
      </template>
      <template #guns="scope:any">
        <DictTag :options="ChargerGunStateEnum" v-for="(i,k) in scope.row.guns" :key="k" :value="i.state" :text="`${i.no}: `" />
      </template>
      <template #group="scope:any">
        <el-tag class="mr5" v-for="(i,k) in scope.row.group" :key="k">{{ i.name }}</el-tag>
      </template>
      <template #menuSlot="scope:any">
        <div class="menu-btn">
          <el-tooltip class="box-item" effect="dark" :content="t('business.charger.action.chargerGunList')" placement="top">
            <el-button link type="primary" class="iconfont icon-chongdianqiang2" @click="handleChargerGunList(scope.row)" />
          </el-tooltip>
          <el-divider direction="vertical" />
        </div>

        <el-dropdown @command="handleOperate" v-has-permi="['business:charger:operate']">
          <span class="el-dropdown-link">
            操作<el-icon class="el-icon--right"><arrow-down /></el-icon
          ></span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="(i,k) in scope.row.guns" :key="k" :command="{ command: 'startCharge', row: scope.row, gunId: i.id }">启动充电({{i.no}}枪)</el-dropdown-item>
              <el-dropdown-item :command="{ command: 'timeConfig', row: scope.row }" divided>下发校时</el-dropdown-item>
              <el-dropdown-item :command="{ command: 'priceConfig', row: scope.row }">下发计价规则</el-dropdown-item>
              <el-dropdown-item :command="{ command: 'qrcodeConfig', row: scope.row }">下发二维码</el-dropdown-item>
              <el-dropdown-item :command="{ command: 'reboot', row: scope.row }" divided>下发重起</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </yt-crud>
    <ChargerGunListDialog ref="chargerGunListRef" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" setup>
import { IColumn } from '@/components/common/types/tableCommon'
import { ComponentInternalInstance } from 'vue'
import {
  getChargerList,
  deleteCharger,
  saveCharger,
  batchDeleteChargers,
  startCharge,
  timeConfig,
  qrcodeConfig, priceConfig, reboot, changeStatus
} from '@/api/business/charger'
import {optionSelect as productOptionSelect} from '@/api/platform/product'
import {ProductsVo} from '@/api/platform/product/types'
import YtCrud from '@/components/common/yt-crud.vue'
import {PriceVO} from '@/api/business/priceCharge/types'
import {StationVo} from '@/api/business/station/types'
import {optionSelect as stationOptionSelect } from '@/api/business/station'
import {optionSelect as priceOptionSelect} from '@/api/business/priceCharge'
import {useI18n} from 'vue-i18n'
import {ArrowDown} from '@element-plus/icons-vue'
import ChargerGunListDialog from '@/views/business/charger/modules/ChargerGunList.vue'

const { t } = useI18n()

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { EnableStatusEnum, OnlineStatusEnum, ChargerGunStateEnum } = toRefs<any>(proxy?.useEnum('enable_status_enum', 'online_status_enum', 'charger_gun_state_enum'))

const chargerGunListRef = ref()

const state = reactive({
  page: {
    pageSize: 30,
    pageNum: 1,
    sortMap: { stationId: 'asc', name: 'asc', createTime: 'desc'},
  },
  total: 0,
  loading: false,
  query: {},
})

// 产品字典
const productOptions = ref<ProductsVo[]>([])
const stationOptions = ref<StationVo[]>([])
const priceOptions = ref<PriceVO[]>([])

const formProps = ref({
  width: 600,
})

const column = ref<IColumn[]>([
  {
    label: t('business.charger.productKey'),
    key: 'productKey',
    type: 'select',
    sortable: false,
    search: false,
    editDisabled: true,
    colSpan: 22,
    componentProps: {
      labelAlias: 'name',
      valueAlias: 'id',
      options: [],
    },
    rules: [{ required: true, message: t('business.charger.validator.productKey') }],
  },
  {
    label: t('business.charger.stationId'),
    key: 'stationId',
    search: true,
    sortable: false,
    type: 'i18nSelect',
    slot: false,
    formHide: false,
    colSpan: 22,
    rules: [{ required: true, message: t('business.charger.validator.stationId') }],
    componentProps: {
      labelAlias: 'name',
      valueAlias: 'id',
      options: [],
    },
  },
  {
    label: t('business.charger.priceId'),
    key: 'priceId',
    search: true,
    sortable: false,
    type: 'select',
    slot: false,
    formHide: false,
    colSpan: 22,
    rules: [{ required: true, message:t('business.charger.validator.priceId') }],
    componentProps: {
      labelAlias: 'name',
      valueAlias: 'id',
      options: [],
    },
  },
  {
    label: t('business.charger.name'),
    key: 'name',
    sortable: true,
    componentProps: {
      placeholder: t('business.charger.placeholder.name'),
    },
    rules: [{ required: true, message: t('business.charger.validator.name') }],
  },

  {
    label: t('business.charger.dn'),
    key: 'dn',
    sortable: true,
    componentProps: {
      placeholder: t('business.charger.placeholder.dn'),
    },
    rules: [{ required: true, message: t('business.charger.validator.dn') }],
  },
  {
    label: t('business.charger.guns'),
    key: 'guns',
    search: false,
    formHide: true,
    sortable: false,
    slot: true,
  },
  {
    label: t('business.charger.online'),
    key: 'online',
    type: 'select',
    componentProps: {
      options: OnlineStatusEnum,
    },
    search: true,
    formHide: true,
    sortable: false,
    slot: true,
  },
  {
    label: t('business.charger.status'),
    key: 'status',
    type: 'select',
    componentProps: {
      options: EnableStatusEnum,
    },
    search: true,
    formHide: false,
    sortable: false,
    slot: true,
    rules: [{ required: true, message: t('business.charger.validator.status') }],
  },
  {
    label: t('business.charger.note'),
    key: 'note',
    hide: true,
    formHide: false,
    componentProps: {
      type: 'textarea',
      rows: 2,
    }
  },
  {
    label: t('crud.table.column.createTime'),
    key: 'createTime',
    tableWidth: 180,
    sortable: true,
    type: 'date',
    formHide: true,
  },
])
const crudRef = ref()
const data = ref<any[]>([])
const getData = () => {
  state.loading = true
  getChargerList({
    ...state.page,
    ...state.query,
  })
    .then((res) => {
      data.value = res.data.rows
      state.total = res.data.total
    })
    .finally(() => {
      state.loading = false
    })
}

const getDict = () => {
  productOptionSelect({type: 'Charger', status: 'Enabled' }).then((res) => {
    productOptions.value = res.data || []
    column.value.forEach((item) => {
      if (item.key === 'productKey') {
        item.componentProps.options = productOptions.value.map((item)=> {
          return {id: item.productKey, name: item.name}
        })
      }
    })
  })

  stationOptionSelect({ status: 'Enabled' }).then((res) => {
    stationOptions.value = res.data || []
    column.value.forEach((item) => {
      if (item.key === 'stationId') {
        item.componentProps.options = stationOptions.value.map((item)=> {
          return {id: item.id, name: item.name}
        })
      }
    })
  })

  priceOptionSelect().then((res) => {
    priceOptions.value = res.data || []
    column.value.forEach((item) => {
      if (item.key === 'priceId') {
        item.componentProps.options = priceOptions.value
      }
    })
  })
}
getDict()

// 保存数据
const onSave = async ({ data, cancel }: any) => {
  state.loading = true
  await saveCharger(toRaw(data)).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    cancel()
    getData()
  }).finally(()=>{
    state.loading = false
  })
}
// 弹窗前置操作
const openBeforeFun = ({ type }) => {
  if (type === 'add') { /* empty */ } else if (type === 'update') { /* empty */ }
}

const handleChargerGunList = (row: any) => {
  chargerGunListRef.value.openDialog(row)
}

const handleSuccess = () => {}

/** 状态修改  */
const handleStatusChange = async (row: any) => {
  if(!row.id)  return
  try {
    await proxy?.$modal.confirm(row.status === 'Enabled' ? t('crud.action.tooltip.enable') : t('crud.action.tooltip.disabled'))
    await changeStatus(row.id, row.status)
    ElMessage.success(t('operate.tooltip.success'))
    getData()
  } catch (err) {
    row.status = row.status === 'Enabled' ? 'Disabled' : 'Enabled'
  }
}

// 删除
const handleDelete = async (row: any) => {
  state.loading = true
  if (row instanceof Array) {
    batchDeleteChargers(row.map((m) => m.id)).then(()=>{
      ElMessage.success(t('operate.tooltip.success'))
      getData()
    }).finally(()=>{
      state.loading = false
    })
  } else {
    deleteCharger(row.id).then(()=>{
      ElMessage.success(t('operate.tooltip.success'))
      getData()
    }).finally(()=>{
      state.loading = false
    })
  }
}

const handleOperate = (commandObj: any ) => {
  const { command, row, gunId } = commandObj
  switch (command) {
    case 'startCharge':
      handleStartCharge(row, gunId)
      break
    case 'timeConfig':
      handleTimeConfig(row)
      break
    case 'qrcodeConfig':
      handleQrcodeConfig(row)
      break
    case 'priceConfig':
      handlePriceConfig(row)
      break
    case 'reboot':
      handleReboot(row)
      break
  }
}

const handleStartCharge = async (row: any, gunId: string) => {
  state.loading = true

  console.log({ id: row.id, gunId: gunId})
  startCharge({ id: row.id, gunId: gunId}).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    getData()
  }).finally(()=>{
    state.loading = false
  })
}

const handleTimeConfig = async (row: any) => {
  state.loading = true
  timeConfig(row.id).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    getData()
  }).finally(()=>{
    state.loading = false
  })
}

const handleQrcodeConfig = async (row: any) => {
  state.loading = true
  await qrcodeConfig(row.id).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    getData()
  }).finally(()=>{
    state.loading = false
  })
}

const handlePriceConfig = async (row: any) => {
  state.loading = true
  await priceConfig(row.id).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    getData()
  }).finally(()=>{
    state.loading = false
  })
}

const handleReboot = async (row: any) => {
  state.loading = true
  await reboot(row.id).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    getData()
  }).finally(()=>{
    state.loading = false
  })
}

const multipleSelection = ref<{ id: string }[]>([])

const onChange = (data) => {
  multipleSelection.value = data
}


const options = reactive({
  ref: 'crudRef',
  formProps,
  data,
  column,
})
</script>
